package top.yaofengqiao.springcloudsimple.auth.biz.infrastructure.repository;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.springframework.stereotype.Repository;
import top.yaofengqiao.springcloudsimple.auth.biz.domain.auth.model.entity.RoleEntity;
import top.yaofengqiao.springcloudsimple.auth.biz.domain.auth.repository.IRoleRepository;
import top.yaofengqiao.springcloudsimple.auth.biz.infrastructure.dao.SysRoleMapper;
import top.yaofengqiao.springcloudsimple.auth.biz.infrastructure.dao.SysUserRoleMapper;
import top.yaofengqiao.springcloudsimple.auth.biz.infrastructure.po.SysRolePO;
import top.yaofengqiao.springcloudsimple.auth.biz.infrastructure.po.SysUserRolePO;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author yfq
 * @date 2024/6/1 15:07
 * @description
 */
@Repository
public class RoleRepository implements IRoleRepository {
    @Resource
    private SysRoleMapper sysRoleMapper;
    @Resource
    private SysUserRoleMapper sysUserRoleMapper;

    @Override
    public List<RoleEntity> queryByUserId(long userId) {
        List<SysUserRolePO> userRoles = sysUserRoleMapper.selectList(Wrappers.<SysUserRolePO>lambdaQuery().eq(SysUserRolePO::getUserId, userId));

        if (CollUtil.isEmpty(userRoles)) return Collections.emptyList();

        List<Long> roleIds = userRoles.stream().map(SysUserRolePO::getRoleId).collect(Collectors.toList());

        List<SysRolePO> roles = sysRoleMapper.selectList(Wrappers.<SysRolePO>lambdaQuery().in(SysRolePO::getId, roleIds));

        return roles.stream().map(this::buildRoleEntity).collect(Collectors.toList());
    }

    private RoleEntity buildRoleEntity(SysRolePO sysRolePO) {
        if (sysRolePO == null) return null;

        return RoleEntity.builder()
                .id(sysRolePO.getId())
                .name(sysRolePO.getName())
                .code(sysRolePO.getCode())
                .sort(sysRolePO.getSort())
                .dataScope(sysRolePO.getDataScope())
                .dataScopeDeptIds(sysRolePO.getDataScopeDeptIds())
                .status(sysRolePO.getStatus())
                .type(sysRolePO.getType())
                .remark(sysRolePO.getRemark())
                .build();
    }
}
